/**
 * 
 */
package org.mspring.crm.service.impl;

import org.apache.log4j.Logger;
import org.mspring.crm.dao.permission.UserDao;
import org.mspring.crm.entity.permission.User;
import org.mspring.crm.service.UserService;
import org.mspring.platform.common.CodecUtils;
import org.mspring.platform.dao.support.Page;
import org.mspring.platform.dao.support.QueryAppender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Gao Youbo
 * @since Feb 20, 2012
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    private static final Logger log = Logger.getLogger(UserServiceImpl.class);

    private UserDao userDao;

    @Autowired
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.mspring.crm.service.UserService#findUserByName(java.lang.String)
     */
    public User findUserByName(String username) {
        // TODO Auto-generated method stub
        return userDao.findUnique("from User m where m.name = ?", username);
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.mspring.crm.service.UserService#getPasswordByName(java.lang.String)
     */
    public String getPasswordByName(String username) {
        // TODO Auto-generated method stub
        User user = userDao.findUnique("select u from User u where u.name = ?", username);
        if (user != null) {
            return user.getPassword();
        }
        return null;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.mspring.crm.service.UserService#validateUser(java.lang.String,
     *      java.lang.String)
     */
    public User validateUser(String username, String password) {
        // TODO Auto-generated method stub
        return validateUser(username, password, false);
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.mspring.crm.service.UserService#validateUser(java.lang.String,
     *      java.lang.String, boolean)
     */
    public User validateUser(String username, String password, boolean encrypt) {
        // TODO Auto-generated method stub
        return userDao.findUnique("select m from User m where m.name = ? and m.password = ?", new String[] { username, encrypt ? password : CodecUtils.encrypt(password) });
    }

    /* (non-Javadoc)
     * @see org.mspring.crm.service.UserService#findPageUser()
     */
    public Page<User> findPageUser(Page<User> page, QueryAppender queryAppender) {
        // TODO Auto-generated method stub
        return userDao.findPage(page, queryAppender);
    }

}
